#include "image.h"

Image::Image(wxString path) {
	texture = new GLuint[1];
	glGenTextures(1, &texture[0]);
	glBindTexture(GL_TEXTURE_2D, *texture);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	if (!wxFileExists(path)) {
		wxMessageBox(wxT("Error in loading image:\nFile does not exist."));
		exit(1);
	}

	wxImage *image = new wxImage(path);
	width = image->GetWidth();
	height = image->GetHeight();

	//If the width and height are not powers of 2, we can resize them with some tricky bitwise operations
	if (width & (width - 1) == 0) {
		correctWidth = width - 1;
		for (int i = 0; width >> i != 0; ++i)
			correctWidth |= width >> i;
		++correctWidth;
	}

	if (height & (height - 1) == 0) {
		int correctHeight = height - 1;
		for (int i = 0; width >> i != 0; ++i)
			correctHeight |= height >> i;
		++correctHeight;
	}

	GLubyte *imageData = image->GetData();

	glTexImage2D(GL_TEXTURE_2D,
		0,
		3,
		correctWidth,
		correctHeight,
		0,
		GL_RGB,
		GL_UNSIGNED_BYTE,
		imageData);

	free(imageData);

	textureX = correctWidth / width;
	textureY = correctHeight / height;
}

void Image::Draw(float x, float y) {
	glLoadIdentity();
	glTranslatef(x, y, 0);

	glBindTexture(GL_TEXTURE_2D, *texture);

	glBegin(GL_QUADS);
		glTexCoord2f(0, 0);
		glVertex2f(x, y);

		glTexCoord2f(textureX, 0);
		glVertex2f(x + width, y);

		glTexCoord2f(textureX, textureY);
		glVertex2f(x + width, y + height);

		glTexCoord2f(0, textureY);
		glVertex2f(x, y + height);
	glEnd();
}

/*	for (int y = 0; y < height; ++y) {
		for (int x = 0; x < width; ++x) {
			imageData[(x + y * width) * bytesPerPixel + 0] =
					bitmapData[(x + (height - 1 - y) * width) * 3];

			imageData[(x + y * width) * bytesPerPixel + 1] =
					bitmapData[( x + (height - 1 - y) * width) * 3 + 1];

			imageData[(x + y * width) * bytesPerPixel + 2] =
					bitmapData[( x + (height - 1 - y) * width) * 3 + 2];

			if (bytesPerPixel == 4)
				imageData[(x + y * width) * bytesPerPixel + 3] =
					alphaData[x + (height - 1 - y) * width];
		}
	}*/
